<template>
  <div class="app-container">
    <!-- 搜索 -->
    <div class="filter-container">
      <div v-if="checkPermission(['permissions@POST'])" class="filter-button">
        <el-button
          v-permission="['permissions@POST']"
          class="el-icon-edit"
          type="primary"
          @click="add"
        >新增
        </el-button>
      </div>
      <div class="filter-form">
        <el-form :model="filter" :inline="true" size="medium">
          <el-form-item label="">
            <el-input v-model="filter.keyword" placeholder="权限名" />
          </el-form-item>
        </el-form>
        <div>
          <el-button
            v-permission="['permissions@GET']"
            @click="getList"
          >
            搜索
          </el-button>
          <el-button
            v-permission="['permissions@GET']"
            @click="resetForm"
          >重置
          </el-button>
          <el-button
            plain
            @click="handleTreeExpandCompress"
          >
            {{ isExpand ? '全部收起' : '全部展开' }}
          </el-button>
        </div>
      </div>
    </div>
    <div v-loading="listLoading" class="content-container">
      <el-table
        ref="table"
        :cell-style="{ textAlign: 'center' }"
        :data="list"
        border
        style="width: 100%"
        :default-expand-all="isExpand"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        row-key="id"
        :header-cell-class-name="headerStyle"
        size="mini"
      >
        <el-table-column prop="name" label="权限名称">
          <template slot-scope="{ row }">
            <el-tag v-if="row.is_menu==1 && row.p_id == 0" size="mini">目录</el-tag>
            <el-tag v-if="row.is_menu==1 && row.p_id > 0" size="mini" type="warning">菜单</el-tag>
            <el-tag v-if="row.is_menu == 0" size="mini" type="info">权限</el-tag>
            <span> {{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="权限状态" size="medium">
          <template slot-scope="{ row }">
            <el-tag v-if="row.status == 1">正常</el-tag>
            <el-tag v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="api路由">
          <template slot-scope="{ row }">
            <el-tag v-if="row.url">
              <span>{{ row.url }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="icon" label="图标">
          <template slot-scope="{ row }">
            <i :class="row.icon" />
          </template>
        </el-table-column> -->
        <el-table-column prop="path" label="组件路径">
          <template slot-scope="{ row }">
            <el-tag v-if="row.path">
              <span>{{ row.path }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="method" label="方法">
          <template slot-scope="{ row }">
            <el-tag v-if="row.method">{{ row.method.toUpperCase() }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="checkPermission(['permissions@PUT','permissions@DELETE'])" label="操作" width="250px" fixed="right">
          <template slot-scope="{ row }">
            <el-button
              v-permission="['permissions@PUT']"
              type="text"
              @click="edit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="row.id !==1"
              v-permission="['permissions@DELETE']"
              type="text"
              class="button-red"
              @click="del(row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="permissionRules"
        label-width="100px"
      >
        <el-form-item label="是否为菜单">
          <el-radio-group v-model="editForm.is_menu">
            <el-radio-button :label="true">是</el-radio-button>
            <el-radio-button :label="false">否</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限名称: " prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="权限状态: " prop="status">
          <el-radio v-model="editForm.status" :label="1">正常</el-radio>
          <el-radio v-model="editForm.status" :label="2">禁用</el-radio>
        </el-form-item>
        <el-form-item label="api路由: " prop="url">
          <el-input v-model="editForm.url" />
        </el-form-item>
        <el-form-item v-if="editForm.is_menu" label="是否隐藏: " prop="hidden">
          <el-radio v-model="editForm.hidden" :label="1">是</el-radio>
          <el-radio v-model="editForm.hidden" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item
          v-if="editForm.is_menu"
          label="组件路径: "
          prop="path"
        >
          <el-input v-model="editForm.path" />
        </el-form-item>

        <el-form-item v-if="editForm.is_menu" label="icon">
          <el-input v-model="editForm.icon" />
          <!-- <el-link type="primary" href="http://www.fontawesome.com.cn/faicons/" target="_blank">图标源</el-link> -->
          <!-- <e-icon-picker v-model="editForm.icon" prop="icon" /> -->
        </el-form-item>
        <el-form-item
          v-if="!editForm.is_menu"
          label="方法选择: "
          :required="true"
          prop="method"
        >
          <el-radio v-model="editForm.method" label="POST" border />
          <el-radio v-model="editForm.method" label="GET" border />
          <el-radio v-model="editForm.method" label="*" border />
          <el-radio v-model="editForm.method" label="PUT" border />
          <el-radio v-model="editForm.method" label="DELETE" border />
        </el-form-item>
        <el-form-item label="请选择父级: ">
          <SelectTree
            v-if="dialogVisible"
            :props="defaultProps"
            :nodes="permissions"
            :value="checkedPermission"
            @setId="setId($event)"
          />
        </el-form-item>
        <el-form-item label="排序: " prop="sort">
          <el-input-number v-model="editForm.sort" :min="1" @change="handleChange" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submit">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SelectTree from './components/selectTree'
import checkPermission from '@/utils/permission' // 权限判断函数
import {
  getPermissionList,
  getAllPermissions,
  addPermissions,
  delPermissions,
  updatePermissions
} from '@/api/auth'

const defaultPermission = {
  name: '',
  title: '',
  icon: '',
  path: '',
  status: '',
  method: '*',
  id: undefined,
  p_id: 0,
  root: false,
  hidden: 2,
  url: '',
  is_menu: true,
  sort: 100
}
export default {
  name: 'PagePermission',
  components: { SelectTree },
  data() {
    return {
      isExpand: true,
      filter: {
        keyword: ''
      },
      list: [],
      listLoading: false,
      dialogVisible: false,
      title: '',
      editForm: Object.assign({}, defaultPermission),
      permissionRules: {
        name: [
          { required: true, trigger: 'blur', message: '请输入名称' }
        ],
        status: [
          { required: true, trigger: 'blur', message: '请选择状态' }
        ]
      },
      permissions: [],
      checkedPermission: 0,
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    checkPermission,
    headerStyle({ row, rowIndex }) {
      return 'table-th'
    },
    getList() {
      this.listLoading = true
      getPermissionList(this.filter).then((response) => {
        const { list } = response.data
        this.list = list
        this.listLoading = false
      })
    },
    submit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          if (this.editForm.id !== undefined) {
            updatePermissions(this.editForm).then(() => {
              this.$message.success('修改成功')
              this.getList()
              this.dialogVisible = false
            })
          } else {
            addPermissions(this.editForm).then(() => {
              this.$message.success('添加成功')
              this.getList()
              this.dialogVisible = false
            })
          }
        } else {
          return false
        }
      })
    },
    add() {
      this.editForm = Object.assign({}, defaultPermission)
      this.getAllPermission()
      this.title = '新增权限节点'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
    },
    async edit(item) {
      await this.getAllPermission()
      this.editForm = Object.assign({}, item, {
        method: item.method.toUpperCase(),
        root: item.p_id === 0,
        is_menu: item.is_menu
      })
      this.checkedPermission = item.p_id
      this.title = '编辑权限 | ' + item.name
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
    },
    resetForm() {
      this.filter.keyword = ''
      this.getList()
    },
    del(item) {
      this.$confirm('此操作将永久删除该节点, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delPermissions(item.id).then(() => {
            this.$message.success('删除成功')
            this.getList()
          })
        })
    },
    setId(id) {
      this.editForm.p_id = id
    },
    handleChange(value) {
      this.editForm.sort = value
    },
    getAllPermission() {
      getAllPermissions().then((response) => {
        const { list } = response.data
        const permissionNode = [
          {
            id: 0,
            name: '根节点',
            title: '根节点'
          }
        ]
        this.permissions = permissionNode.concat(list)
      })
    },

    // 展开收拢树状
    handleTreeExpandCompress() {
      this.isExpand = !this.isExpand
      this.expandRowExpansion(this.list, this.isExpand)
    },
    expandRowExpansion(data, isExpand) {
      data.forEach(item => {
        this.$refs.table.toggleRowExpansion(item, isExpand)
        if (item?.children) {
          this.expandRowExpansion(item.children, isExpand)
        }
      })
    }
  }
}
</script>
